/**
 * 友链
 */

const { validationResult } = require("express-validator");
const { CODE_OK, CODE_Internal_Server_Error } = require("@root/config/index");
const { poolPromise } = require("@root/db/index");
const { validateParams } = require("@root/utils/peak-tools.js");

/**
 * 获取友链列表
 */
async function selectBlogrollList(req, res, next) {
  if (validateParams({ req, res, validationResult })) return;

  try {
    const { currentPage = 1, pageSize = 10, is_active = "" } = req.query;

    const select_blogroll_all_sql = `select * from blogroll where if(? = '', true, is_active = ?)`;

    const [list_all] = await poolPromise.execute(select_blogroll_all_sql, [is_active, is_active]);
    const total = list_all.length;
    if (!total) {
      return res.status(CODE_OK).json({
        code: CODE_OK,
        msg: "暂无数据",
        total,
        currentPage,
        pageSize,
        data: [],
      });
    }
    const startIndex = (currentPage - 1) * pageSize;
    const select_blogroll_sql = `${select_blogroll_all_sql} LIMIT ? OFFSET ?`;

    const [list] = await poolPromise.execute(select_blogroll_sql, [
      is_active,
      is_active,
      String(pageSize),
      String(startIndex),
    ]);
    res.status(CODE_OK).json({
      code: CODE_OK,
      msg: "获取友链成功",
      total,
      currentPage: Number(currentPage),
      pageSize: Number(pageSize),
      data: list,
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 新增友链
 */
async function insertBlogroll(req, res, next) {
  if (validateParams({ req, res, validationResult })) return;
  try {
    // 默认友链禁用
    let { site_name, site_url, site_icon = "", email = "", description, is_active = 0 } = req.body;
    site_icon = site_icon || site_url + "/favicon.ico"; // 默认网站图标
    const insert_blogroll_sql = `insert into blogroll(site_name, site_url,site_icon, email, description, is_active) values(?,?,?,?,?,?)`;
    let [{ affectedRows: blogroll_affectedRows }] = await poolPromise.execute(insert_blogroll_sql, [
      site_name,
      site_url,
      site_icon,
      email,
      description,
      is_active,
    ]);
    if (!blogroll_affectedRows) {
      return res.status(CODE_Internal_Server_Error).json({
        code: CODE_Internal_Server_Error,
        msg: "添加友链失败",
        data: null,
      });
    }
    res.status(CODE_OK).json({
      code: CODE_OK,
      msg: "添加友链成功",
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 修改友链
 */
async function updateBlogroll(req, res, next) {
  if (validateParams({ req, res, validationResult })) return;
  try {
    const {
      id,
      site_name,
      site_url,
      site_icon = null,
      email = null,
      description,
      is_active = 1,
    } = req.body;
    const update_blogroll_sql = `update blogroll set site_name = ?, site_url = ?,site_icon = ?, email = ?, description = ?, is_active = ? where id = ?`;
    let [{ affectedRows: blogroll_affectedRows }] = await poolPromise.execute(update_blogroll_sql, [
      site_name,
      site_url,
      site_icon,
      email,
      description,
      is_active,
      id,
    ]);
    if (!blogroll_affectedRows) {
      return res.status(CODE_Internal_Server_Error).json({
        code: CODE_Internal_Server_Error,
        msg: "修改友链失败",
        data: null,
      });
    }
    res.status(CODE_OK).json({
      code: CODE_OK,
      msg: "修改友链成功",
      data: null,
    });
  } catch (error) {
    next(error);
  }
}

/**
 * 删除友链
 */
async function deleteBlogroll(req, res, next) {
  if (validateParams({ req, res, validationResult })) return;
  try {
    const { ids } = req.body;
    const delete_blogroll_sql = `delete from blogroll where id in (${new Array(ids.length)
      .fill("?")
      .join(",")})`;
    let [{ affectedRows: blogroll_affectedRows }] = await poolPromise.execute(
      delete_blogroll_sql,
      ids
    );
    if (!blogroll_affectedRows) {
      return res.status(CODE_Internal_Server_Error).json({
        code: CODE_Internal_Server_Error,
        msg: "删除友链失败",
        data: null,
      });
    }

    res.status(CODE_OK).json({
      code: CODE_OK,
      msg: "删除友链成功",
      data: null,
    });
  } catch (error) {
    next(error);
  }
}

module.exports = {
  selectBlogrollList,
  insertBlogroll,
  updateBlogroll,
  deleteBlogroll,
};
